#include "paginationcontroller.h"

#include "databasemanager.h"

PaginationController::PaginationController(DatabaseManager *databaseManager, QObject *parent)
    : QObject(parent)
    , m_databaseManager(databaseManager)
{

}

// 设置分页
void PaginationController::setupPagination(int totalRecords, int pageSize)
{

}

int PaginationController::currentPage()
{
    return m_currentPage;
}

int PaginationController::totalPages() {
    QString currtableName(m_databaseManager->m_currentTable);
    m_Records = m_databaseManager->getTotalRecords(DatabaseManager::TABLE_NAMES.key(currtableName));

    m_totalPages = m_Records / m_pageSize;
    if(m_Records % m_pageSize || m_totalPages == 0) {
        m_totalPages += 1;
    }
    return m_totalPages;
}

void PaginationController::gotoPage(int page)
{
    // 获取总页数
    int total = m_totalPages;

    // 判断是否大于总页数
    if(page > m_totalPages)
    {
        page = m_totalPages;
    }

    // 设置页面
    setCurrentPage(page);
}

void PaginationController::nextPage()
{
    int page = m_currentPage + 1;
    if(page <= m_totalPages) {
        setCurrentPage(page);
    }

    // 发送信号
}

void PaginationController::prevPage()
{
    // 获取当前页数
    int page = m_currentPage - 1;
    if(page >= 0) {
        setCurrentPage(page);
    }

    // 发送信号
}

void PaginationController::firstPage()
{
    setCurrentPage(1);
    // 获取总页数

    // 设置页数

    // 判断页数，是否变化

    // 发送信号
}

void PaginationController::lastPage()
{
    // 获取总页数
    int page = m_totalPages;// 获取总页数

    setCurrentPage(page);
    // 设置页数

    // 发送信号
}

void PaginationController::setCurrentPage(int currentPage)
{
//    qDebug() << "setCurrentPage:" << currentPage;
    m_currentPage = currentPage;

    if (!m_databaseManager) {
            qWarning() << "DatabaseManager not initialized!";
            return;
        }

    QString currtableName(m_databaseManager->m_currentTable);
    totalPages(); // 更新总页数


//    m_databaseManager->refreshTable(currtableName, m_currentPage, m_pageSize);

    m_databaseManager->pagingQuerySql(currtableName, m_currentPage);

//    qDebug() << "currentPage:" << m_currentPage << "totalPage:" << m_totalPages;

    emit paginationUpdated(m_currentPage, m_totalPages);
}

int PaginationController::Records()
{
    QString currtableName(m_databaseManager->m_currentTable);
    m_Records = m_databaseManager->getTotalRecords(DatabaseManager::TABLE_NAMES.key(currtableName));

    qDebug() << "m_Records:" << m_Records;
    return m_Records;
}

int PaginationController::pageSize()
{
    return m_pageSize;
}
